package com.lebang.controller.buss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.ConfigRecord;
import com.lebang.common.ExeclUtil;
import com.lebang.common.Login;
import com.lebang.common.utils.MD5;
import com.lebang.component.AsyncsComponent;
import com.lebang.component.CommonComponent;
import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.task.LbbCommon;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.example.LbbMemberRecordExample;
import com.lebang.example.TaskClassifyExample;
import com.lebang.example.TaskTagExample;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.Status;
import com.lebang.model.enums.buss.*;
import com.lebang.model.vo.buss.TaskSearchVo;
import com.lebang.service.TaskClassifyService;
import com.lebang.service.TaskScreenshotService;
import com.lebang.service.TaskTagService;
import com.lebang.service.buss.CustomService;
import com.lebang.service.buss.MemberRecordService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.task.TaskService;
import com.lebangweb.common.DateUtil;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 通用型任务
 *
 * @author weizx
 * @className CommonController
 * @date 2018年8月23日 下午2:20:02
 */
@Controller
public class CommonController {

    @Autowired
    private CommonComponent commonComponent;
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private RedisClient redisClient;




    @Autowired
    @Qualifier(value = "commonTaskService")
    private TaskService<LbbCommon> commonService;

    @Autowired
    private MemberService memberService;
    @Autowired
    private CustomService customService;
    @Autowired
    private AsyncsComponent asyncsComponent;
    @Autowired
    private TaskScreenshotService taskScreenshotService;
    @Autowired
    private TaskClassifyService taskClassifyService;
    @Autowired
    private TaskTagService taskTagService;
    @Autowired
    private RedisSdkClient redisSdkClient;


    /**
     * 列表入口
     *
     * @param model
     * @param session
     * @return
     * @author weizx
     * @date 2018年8月24日 下午2:34:32
     */
    @Login
    @RequestMapping(value = {"/common/list"}, method = {RequestMethod.GET})
    public String list(Model model, HttpSession session) {
        model.addAttribute("booleans", Booleans.values());
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("Status", Status.values());
        return "/common/list";
    }

    /**
     * 列表接口
     *
     * @param vo
     * @return
     * @author weizx
     * @date 2018年8月24日 下午2:34:39
     */
    @Login
    @RequestMapping(value = {"/common/list"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> pagging(TaskSearchVo vo) {
        Map<String, Object> data = commonComponent.pagging(vo, 0);
        return data;
    }

    @Login
    @RequestMapping(value = {"/common/status"}, method = {RequestMethod.POST})
    @ResponseBody
    public String status(@RequestParam(value = "taskid") String taskid) {
        LbbCommon task = commonService.taskInfoByTaskId(taskid);
        if (task == null) {
            return "任务不存在！";
        }
        if (task.getStatus().equals(Status.Off)) {
            task.setStatus(Status.On);
        } else {
            task.setStatus(Status.Off);
        }
        TaskScreenshot taskScreen = taskScreenshotService.selectByTaskId(taskid);
        taskScreen.setStatus(task.getStatus().name());
        task.setTaskScreenshot(taskScreen);
        commonService.updateTask(task);
        return "状态已修改！";
    }

    @Login
    @RequestMapping(value = {"/common/del"}, method = {RequestMethod.POST})
    @ResponseBody
    public String del(@RequestParam(value = "taskid") String taskid) {
        LbbCommon task = commonService.taskInfoByTaskId(taskid);
        if (task == null) {
            return "任务不存在！";
        }
        commonService.deleteTask(task);
        return "已删除！";
    }

    @Login
    @RequestMapping(value = {"/common/dels"}, method = {RequestMethod.POST})
    @ResponseBody
    public String dels(@RequestParam(value = "memberId") String memberId, @RequestParam(value = "taskId") String taskId
    ) {
        LbbMemberRecord mr = memberRecordService.getByMemberIdandTaskid(taskId, memberId, TaskStatus.CheckFailure.name());
        // 未审核的用户
        if (mr == null) {
            return "号码不存在！";
        }
        mr.setRemark(TaskStatus.None.name());
        memberRecordService.updateRecord(mr);
        return "已剔除！";
    }

    @Login
    @RequestMapping(value = {"/common/insert"}, method = {RequestMethod.GET})
    public String insert(Model model) {
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("booleans", Booleans.values());
        model.addAttribute("customlist", customService.getAllCustomList());
        TaskClassifyExample taskClassifyExample = new TaskClassifyExample();
        taskClassifyExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        TaskTagExample taskTagExample = new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        model.addAttribute("taskClassifys",taskClassifyService.selectByEx(taskClassifyExample));
        model.addAttribute("taskTags",taskTagService.selectByEx(taskTagExample));
        return "/common/edit";
    }

    @Login
    @RequestMapping(value = {"/common/edit/{taskid}"}, method = {RequestMethod.GET})
    public String edit(@PathVariable(value = "taskid") String taskid, Model model) {
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        LbbCommon task = commonService.taskInfoByTaskId(taskid);
        TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(taskid);
        model.addAttribute("tags",taskScreenshotService.selectRelation(taskid));
        model.addAttribute("taskScreenshot",taskScreenshot);
        model.addAttribute("customlist", customService.getAllCustomList());
        model.addAttribute("task", task);
        TaskClassifyExample taskClassifyExample = new TaskClassifyExample();
        taskClassifyExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        TaskTagExample taskTagExample = new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        model.addAttribute("taskClassifys",taskClassifyService.selectByEx(taskClassifyExample));
        model.addAttribute("taskTags",taskTagService.selectByEx(taskTagExample));
        return "/common/edit";
    }

    @Login
    @RequestMapping(value = {"/common/save"}, method = {RequestMethod.POST})
    @ResponseBody
    @ConfigRecord
    public JsonData save(LbbCommon task,TaskScreenshot taskScreenshot,@RequestParam(value = "file", required = false) MultipartFile file) {
        task.setIsMultiword(0);
        taskScreenshot.setIsMultiword(0);
        taskScreenshot.setCategory(TaskCategory.Common.name());
        if(TextUtil.isEmpty(task.getLessTime())){
            task.setLessTime(0);
        }
        if(TextUtil.isEmpty(task.getWaitTime())){
            task.setWaitTime(0);
        }
        if(TextUtil.isEmpty(task.getWaitCount())){
            task.setWaitCount(0);
        }
        if(TextUtil.isEmpty(task.getBussAmount())){
            task.setBussAmount(task.getIncrease());
        }

        if (null == task.getTaskId() || "".equals(task.getTaskId())) {
            String taskId = UUIDUtil.L();
            task.setTaskId(taskId);
            taskScreenshot.setTaskId(taskId);
            try {
                asyncsComponent.recordToMember(task.getTitle(), taskId);
                task.setTaskScreenshot(taskScreenshot);
                commonService.insertTask(task);
                return Callback.success("200", "上传成功!", null);
            } catch (Exception e) {
                e.printStackTrace();
                return Callback.fail("200", "上传失败!", null);

            }

        } else {
            LbbCommon co = commonService.taskInfoByTaskId(task.getTaskId());
            task.setId(co.getId());
            task.setTaskScreenshot(taskScreenshot);
            commonService.updateTask(task);

        }
        return Callback.success("200", "上传成功!", null);
    }

    @Login
    @RequestMapping(value = "/common/checkList", method = {RequestMethod.GET})
    public String checkList(Model model) {
        model.addAttribute("taskStatus", TaskStatus.values());
        return "/common/checkList";
    }

    @Login
    @RequestMapping(value = "/common/checkList", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getCheckList(String status, String stime, String etime, Integer offset, Integer limit,
                                            String customer, String title, String phone) {
        String category = TaskCategory.Common.name();
        return memberRecordService.pagging(category, status, stime, etime, offset, limit, title, customer, phone, 0);
    }

    @Login
    @RequestMapping(value = "/common/upCheck", method = {RequestMethod.GET})
    public String upCheck(Model model) {
        // commonService.get
        List<Map<String, Object>> a = commonComponent.task(0);
        // 获取soso和common全部上架的taskid
        model.addAttribute("task", a);
        model.addAttribute("taskStatus", TaskStatus.values());
        return "/common/upCheck";
    }


    @Login
    @RequestMapping(value = {"/common/delData"}, method = {RequestMethod.POST})
    @ResponseBody
    public String delData() {
        commonComponent.delDate();
        return "已清除";
    }







    @Login
    @RequestMapping(value = "/common/getPhone", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getPhone(String taskId, String stime, String etime, HttpServletRequest request,
                                        HttpSession session) {
        return memberRecordService.getPhone(taskId, stime, etime);
    }

    @Login
    @RequestMapping(value = "/common/none", method = {RequestMethod.POST}) // 查不到用户
    @ResponseBody
    public Map<String, Object> none(String taskId, String stime, String etime, HttpServletRequest request,
                                    HttpSession session) {
        return memberRecordService.none(taskId, stime, etime);
    }

    @Login
    @RequestMapping(value = "/common/checkFailure", method = {RequestMethod.POST}) // 无匹配到的 多余的任务记录
    @ResponseBody
    public Map<String, Object> checkFailure(String taskId, String stime, String etime, HttpServletRequest request,
                                            HttpSession session) {
        return memberRecordService.checkFailure(taskId, stime, etime);
    }

    @Login
    @RequestMapping(value = "/common/checkSuccess", method = {RequestMethod.POST}) // 成功
    @ResponseBody
    public Map<String, Object> checkSuccess(String taskId, String stime, String etime, HttpServletRequest request,
                                            HttpSession session) {
        return memberRecordService.checkSuccess(taskId, stime, etime);
    }


//    @Login
    @SuppressWarnings("unlikely-arg-type")
    @RequestMapping(value = "/common/check", method = {RequestMethod.POST})
    @ResponseBody
    public JsonData checks(@RequestParam(value = "memberid") String memberid,
                           @RequestParam(value = "taskid") String taskid, @RequestParam(value = "status") String status,
                           @RequestParam(value = "remark", required = false) String remark,
                           @RequestParam(value = "multiple", required = false) Integer multiple,
                           @RequestParam(value = "check", required = false) String check,
                           HttpServletRequest request, HttpSession session) {
        //验证
        String md5Code = MD5.getMD5Code(memberid + taskid + "check");
        if (!md5Code.equals(check)){
            return Callback.fail("fail", "操作失败", null);
        }
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Common.name());
        if (record == null) {
            return Callback.fail("fail", "操作失败", null);
        }
        List<String> list = new ArrayList<>(1);
        list.add(record.getId().toString());
        int i = commonService.examineAndVerify(list, "", status, remark,multiple==null?1:multiple);
        if (i > 0) {
            memberRecordService.updateMultipleById(multiple,record.getId());
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }

    @Login
    @RequestMapping(value = "/common/detail", method = {RequestMethod.POST})
    @ResponseBody
    public Object detail(@RequestParam(value = "memberid") String memberid,
                         @RequestParam(value = "taskid") String taskid, HttpServletRequest request, HttpSession session) {
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Common.name());
        if (record == null) {
            return "记录不存在！";
        }
        return record;
    }

    @Login
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/common/export", method = {RequestMethod.GET, RequestMethod.POST})
    public void exports(@RequestParam(value = "taskid") String taskid,
                        @RequestParam(value = "upStatus") String upStatus, HttpServletRequest request, HttpServletResponse response,
                        HttpSession session) {
        try {
            LbbCommon task = commonService.taskInfoByTaskId(taskid);
            if (task == null) {
                return;
            }
            if (upStatus == null) {
                return;
            }
            if (upStatus.equals(TaskStatus.WaitCheckout.name()) || "WaitCheckout".equals(upStatus)) {
                List<LbbMemberRecord> records = getRecord(taskid, TaskStatus.WaitCheckout);
                List<Map<String, Object>> data = new ArrayList<>();
                Map<String, String> cols = new LinkedHashMap<>();
                for (LbbMemberRecord record : records) {
                    String strRecode = JSONObject.toJSONString(record);
                    Map<String, Object> json = JSON.parseObject(strRecode);
                    String result = record.getResult();
                    JSONArray array = JSONArray.parseArray(result);
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic" + i, "截图" + (i + 1));
                        String url = j.get("resultImage") + "";// {"image":"http://hotbb.repinchen.cn/common_069221180976bd3a105ff8691750709d.png","title":"图例2"}
                        JSONObject ob = JSONObject.parseObject(url);
                        if (ob == null|| ob.isEmpty()) {
                            continue;
                        }
                        String url1 = ob.getString("image");
                        json.put("pic" + i, url1);
                    }
                    for (int i = 1; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic1" + (i + 1), "步骤" + (i + 1));
                        String url2 = j.get("resultInput") + "";
                        json.put("pic1" + (i + 1), url2);
                    }

                    json.put("createTime", DateUtil.dateToString(record.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    json.put("phone", record.getPhone());
                    json.put("status", record.getStatus().getTitle());
                    data.add(json);
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + URLEncoder.encode(task.getTitle(), "utf-8") + ".xls ");
                Map<String, String> columns = new LinkedHashMap<>();
                columns.put("status", "审核结果");
                columns.put("createTime", "任务时间");
                columns.put("phone", "手机号");
                columns.put("imei", "设备标识");
                columns.putAll(cols);
                ExeclUtil.write(columns, data, response.getOutputStream());
            } else {
                List<LbbMemberRecord> records = getRecord(taskid, TaskStatus.CheckSuccess);
                List<LbbMemberRecord> record2 = getRecord(taskid, TaskStatus.CheckFailure);
                records.addAll(record2);
                List<Map<String, Object>> data = new ArrayList<>();
                Map<String, String> cols = new LinkedHashMap<>();
                for (LbbMemberRecord record : records) {
                    String strRecode = JSONObject.toJSONString(record);
                    Map<String, Object> json = JSON.parseObject(strRecode);
                    String result = record.getResult();
                    JSONArray array = JSONArray.parseArray(result);
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic" + i, "截图" + (i + 1));
                        String url = j.get("resultImage") + "";// {"image":"http://hotbb.repinchen.cn/common_069221180976bd3a105ff8691750709d.png","title":"图例2"}
                        JSONObject ob = JSONObject.parseObject(url);
                        if (ob == null || ob.isEmpty()) {
                            continue;
                        }
                        String url1 = ob.getString("image");
                        json.put("pic" + i, url1);
                    }
                    for (int i = 1; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic1" + (i + 1), "步骤" + (i + 1));
                        String url2 = j.get("resultInput") + "";
                        json.put("pic1" + (i + 1), url2);
                    }
                    json.put("createTime", DateUtil.dateToString(record.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    json.put("phone", record.getPhone());
                    json.put("status", record.getStatus().getTitle());
                    data.add(json);
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + URLEncoder.encode(task.getTitle(), "utf-8") + ".xls ");
                Map<String, String> columns = new LinkedHashMap<>();
                columns.put("status", "审核结果");
                columns.put("createTime", "任务时间");
                columns.put("phone", "手机号");
                columns.put("imei", "设备标识");
                columns.putAll(cols);
                ExeclUtil.write(columns, data, response.getOutputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<LbbMemberRecord> getRecord(String taskid, TaskStatus status) {
        LbbMemberRecordExample lbbMemberRecordExample = new LbbMemberRecordExample();
        LbbMemberRecordExample.Criteria criteria = lbbMemberRecordExample.createCriteria();
        criteria.andTaskIdEqualTo(taskid);
        criteria.andCategoryEqualTo(TaskCategory.Common.name());
        criteria.andNeedCheckedEqualTo("True");
        criteria.andStatusEqualTo(status.name());
        return memberRecordService.getListByExample(lbbMemberRecordExample);

    }

//    @Login
    /**批量审核入口**/
    @PostMapping("/common/checkselectlist")
    @ResponseBody
    public JsonData checklist(String data, String tab, @RequestParam(value = "status") String status,
                              @RequestParam(value = "remark", required = false) String remark,
                              @RequestParam(value = "multiple", required = false) Integer multiple,
                              @RequestParam(value = "checkselectlist", required = false) String checkSelectList) {
        //验证
        String md5Code = MD5.getMD5Code(data + "checkselectlist");
        if (!md5Code.equals(checkSelectList)){
            return Callback.fail("fail", "操作失败", null);
        }
        List<String> list = JSON.parseArray(data, String.class);
        int i = commonService.examineAndVerify(list, tab, status, remark,multiple==null?1:multiple);
        if (i == -1) {
            return Callback.success("success", "操作频繁", null);
        }
        if (i > 0) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }

    @PostMapping("/common/starConmonTask")
    @ResponseBody
    public JsonData starMultiwordTask() {

        if (commonService.starTaskAmount(LocalDateTime.now())) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }

    @PostMapping("/common/task/reload")
    @ResponseBody
    public JsonData taskReload(String taskId) {
        LbbCommon common = commonService.taskInfoByTaskId(taskId);
        if (common != null) {
            if (commonService.taskInitByTaskId(common)) {
                return Callback.success("success", "操作成功", null);
            } else {
                return Callback.fail("fail", "操作失败", null);
            }
        }
        return Callback.fail("fail", "操作失败", null);
    }

    @PostMapping("/common/release")
    @ResponseBody
    public JsonData release(HttpServletRequest request, String data,String release) {
//        List<String> list = Arrays.asList(data.split(","));
        //验证
        String md5Code = MD5.getMD5Code(data + "release");
        if (!md5Code.equals(release)){
            return Callback.fail("fail", "操作失败", null);
        }
        List<String> list = JSON.parseArray(data, String.class);
        commonComponent.release(list);
        return Callback.success("success", "查询成功", null);
    }

    /**
     * 把旧表数据补全到新表内
     * @return
     */
    @Login
    @PostMapping("/common/checkData")
    @ResponseBody
    public JsonData checkData(){

        String uuid = UUIDUtil.M();
        //boolean lock = redisClient.tryGetDistributedLock("COMMONCHECK:KEY", uuid, 10000);
        boolean lock = redisSdkClient.tryGetDistributedLock("COMMONCHECK:KEY", uuid, 10000);
        if (!lock) {
            return Callback.fail("fail", "勿重复操作", null);
        }

        List<LbbCommon> list = commonService.taskList(null,null);
        try{
            list.forEach(s->{
                TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(s.getTaskId());
                if(taskScreenshot==null){
                    TaskScreenshot taskScreen = new TaskScreenshot(s);
                    taskScreenshotService.insert(taskScreen);

                }
            });
        }catch (Exception e){
            e.printStackTrace();
            return Callback.fail("fail", "操作失败", null);
        }finally {
            //redisClient.releaseDistributedLock("COMMONCHECK:KEY", uuid);
            redisSdkClient.releaseDistributedLock("COMMONCHECK:KEY", uuid);
        }

        return Callback.success("success", "操作成功", null);
    }


    @Login
    @RequestMapping(value = {"/common/copyData/{taskid}"}, method = {RequestMethod.GET})
    public String copyDataInsert(@PathVariable(value = "taskid") String taskid, Model model) {
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        LbbCommon task = commonService.taskInfoByTaskId(taskid);
        task.setId(null);
        task.setTaskId(null);
        TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(taskid);
        model.addAttribute("tags",taskScreenshotService.selectRelation(taskid));
        model.addAttribute("taskScreenshot",taskScreenshot);
        model.addAttribute("customlist", customService.getAllCustomList());
        model.addAttribute("task", task);
        model.addAttribute("taskClassifys",taskClassifyService.selectByEx(null));
        TaskTagExample taskTagExample=new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1);
        model.addAttribute("taskTags",taskTagService.selectByEx(taskTagExample));
        return "/common/edit";
    }


    @Login
    @RequestMapping(value = ("/common/task/list"), method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> taskList(HttpServletRequest request, HttpServletResponse response,String title,String status,int page,int limit) {


        List<Map<String,Object>> list = commonComponent.selectCommon(title,status,(page-1)*limit,limit);
        long count = commonComponent.countComon(title,status);
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("data", list);
        returnMap.put("count", count);
        returnMap.put("code", 0);
        return returnMap;
    }



}
